<template>
  <div class="department">
    <div class="dialog">
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-form
          class="form"
          :model="department"
          :rules="rules"
          label-position="right"
          label-width="100px"
          ref="form"
        >
          <el-form-item label="父级部门" prop="parentID">
            <el-select v-model="department.parentID" placeholder="请选择">
              <el-option
                v-for="item in departments"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="department.name" />
          </el-form-item>
          <el-form-item label="部门描述" prop="description">
            <el-input v-model="department.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelClick">取 消</el-button>
          <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="header">
      <el-form :inline="true" size="small" label-width="84px">
        <el-form-item label="部门名称">
          <el-input v-model="search.name" placeholder="" />
        </el-form-item>
        <el-form-item label="父级部门">
          <el-select v-model="search.departmentID" placeholder="请选择">
            <el-option
              v-for="item in departments"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            @click="getDatas(pageNo, pageSize)"
            >查询</el-button
          >
          <el-button type="primary" size="mini" @click="addData"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-card>
        <el-table
          style="width: 100%"
          row-key="id"
          border
          :data="datas"
          :header-cell-style="{ 'background-color': '#EEEEEE' }"
        >
          <el-table-column prop="name" label="部门名称"></el-table-column>
          <el-table-column
            prop="description"
            label="部门描述"
          ></el-table-column>
          <el-table-column prop="statusID" label="状态">
            <template slot-scope="scope">
              {{ statuses[scope.row.statusID].label }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showDialog(scope.row)" type="text" size="small"
                >修改</el-button
              >
              <el-button @click="onDelete(scope.row)" type="text" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            :total="total"
            :current-page.sync="pageNo"
            :page-sizes="[10, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    <div class="footer"></div>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartment,
  deleteDepartment,
  updateDepartment,
} from "@/api/department";

export default {
  data() {
    return {
      dialog: {
        title: "",
        visible: false,
        update: false,
      },
      statuses: [
        { key: 0, label: "停用" },
        { key: 1, label: "活动" },
        { key: 2, label: "草稿" },
        { key: 3, label: "审批中" },
        { key: 5, label: "由活动状态停用" },
        { key: 6, label: "由草稿状态停用" },
        { key: 7, label: "由审批状态停用" },
      ],
      search: {
        name: "",
        departmentID: null,
      },
      pageNo: 1,
      pageSize: 10,
      total: 0,
      departments: [],
      datas: [],
      department: {
        id: null,
        departmentID: null,
        parentID: null,
        name: "",
        description: "",
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      },
      rules: null,
    };
  },
  created() {
    const vm = this;
    vm.$nextTick(() => {
      vm.getDatas(vm.pageNo, vm.pageSize);
      getDepartments({ page: 0, size: 0 })
        .then((res) => {
          vm.datas = res.data;
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.departments.push({ key: d.departmentID, label: d.name });
          }
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject(err);
        });
    });
  },
  destroyed() {},
  methods: {
    getDatas(pageNo, pageSize) {
      const vm = this;
      getDepartments({ name: vm.search.name, parentid: vm.search.departmentID, page: pageNo, size: pageSize })
        .then((res) => {
          console.info(res.data);
          vm.datas = this.toTree(res.data);
          vm.total = res.count;
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject(err);
        });
    },
    toTree(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach((item) => {
        delete item.children;
      });
      let map = {};
      data.forEach((item) => {
        map[item.departmentID] = item;
      });
      data.forEach((item) => {
        let parent = map[item.parentID];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    addData() {
      const vm = this;
      vm.dialog.title = "添加部门";
      vm.dialog.visible = true;
      vm.dialog.update = false;
      vm.department = {
        id: null,
        departmentID: null,
        parentID: null,
        name: "",
        description: "",
        statusID: 1,
        employeeID_Update: vm.$store.getters.uid,
      };
    },
    showDialog(row) {
      const vm = this;
      vm.dialog.title = "修改部门";
      vm.dialog.visible = true;
      vm.dialog.update = true;
      vm.department = {
        id: row.id,
        departmentID: row.departmentID,
        parentID: row.parentID,
        name: row.name,
        description: row.description,
        statusID: row.statusID,
        employeeID_Update: vm.$store.getters.uid,
      };
    },
    onDelete(row) {
      const vm = this;
      vm.$confirm("是否删除?", "提示信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteDepartment({ ids: row.departmentID })
          .then((res) => {
            vm.$message({
              message: res.message,
              type: "success",
            });
            Promise.resolve(res);
            vm.getDatas({ page: vm.pageNo, size: vm.pageSize });
          })
          .catch((err) => {
            Promise.reject(err);
          });
      });
    },
    cancelClick() {
      this.dialog.visible = false;
    },
    confirmClick() {
      const vm = this;
      if (!vm.dialog.update) {
        addDepartment(vm.department).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas({ page: vm.pageNo, size: vm.pageSize });
        });
      } else {
        updateDepartment(vm.department).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas({ page: vm.pageNo, size: vm.pageSize });
        });
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handlePageChange(val) {
      const vm = this;
      vm.pageNo = val;
      vm.getDatas(vm.pageNo, vm.pageSize);
    },
  },
};
</script>

<style lang="scss" scoped>
.department {
  width: 100%;
  padding: 30px;
  .header {
    margin-bottom: 20px;
  }
  .content {
    margin-bottom: 20px;
  }
  .pagination {
    margin-top: 20px;
  }
}
</style>